package com.example.reactor;

import reactor.core.publisher.Mono;

public class MonoNullTest2 {
    public static void main(String[] args) {

        // 1. 测试 then 操作符
        getData(true) // 返回 null
                .then(Mono.fromRunnable(() -> System.out.println("Entered then operator")))
                .subscribe();

        // 2. 测试 flatMap 操作符
        getData(true)
                .flatMap(result -> {
                    System.out.println("Entered flatMap operator with result: " + result);
                    return Mono.just("FlatMap operator triggered");
                })
                .subscribe();

        // 3. 测试 delayUntil 操作符
        getData(true)
                .delayUntil(result -> {
                    System.out.println("Entered delayUntil operator with result: " + result);
                    return Mono.just("Delayed operator triggered");
                })
                .subscribe();

        // 4. 测试 switchIfEmpty 操作符
        getData(true)
                .switchIfEmpty(Mono.fromRunnable(() -> System.out.println("Entered switchIfEmpty operator")))
                .subscribe();

        System.out.println("---------------------------------------分割线-------------------------------------");

        getData(false) // 返回非空值
                .then(Mono.fromRunnable(() -> System.out.println("Entered then operator")))
                .subscribe();

        getData(false)
                .flatMap(result -> {
                    System.out.println("Entered flatMap operator with result: " + result);
                    return Mono.just("FlatMap operator triggered");
                })
                .subscribe();

        getData(false)
                .delayUntil(result -> {
                    System.out.println("Entered delayUntil operator with result: " + result);
                    return Mono.just("Delayed operator triggered");
                })
                .subscribe();

        getData(false)
                .switchIfEmpty(Mono.fromRunnable(() -> System.out.println("Entered switchIfEmpty operator")))
                .subscribe();
    }

    // 根据入参决定是否返回 null 的方法
    private static Mono<String> getData(boolean returnNull) {
        String result = null;
        if (!returnNull) {
            result = "123";
        }
        System.out.println("Entered " + result);
        return Mono.justOrEmpty(result);
    }
}

